import type {
  // 分类相关
  CategoryResponse,
  CategoryCreate,
  CategoryUpdate,
  CategoryWithChildren,
  BatchCategoryCreate,
  CategoryListParams,

  // 账户相关
  AccountResponse,
  AccountCreate,
  AccountUpdate,
  AccountListParams,

  // 项目相关
  ProjectResponse,
  ProjectCreate,
  ProjectUpdate,
  ProjectListParams,

  // 交易相关
  TransactionResponse,
  TransactionCreate,
  TransactionUpdate,
  BatchTransactionCreate,
  TransactionList,
  TransactionListParams,

  // 统计相关
  TransactionSummary,
  CategorySummary,
  AccountSummary,
  ProjectSummary,
  StatisticsParams,
} from "@/types/accounting";

import { API_BASE_URL } from "./api";

// 基础API配置
const apiConfig = {
  baseURL: `${API_BASE_URL}/api/v1`,
  headers: {
    "Content-Type": "application/json",
  },
};

// 获取认证头
function getAuthHeaders(): Record<string, string> {
  const token = localStorage.getItem("access_token");
  return token ? { Authorization: `Bearer ${token}` } : {};
}

// 处理API响应
async function handleResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(
      errorData.detail || `HTTP error! status: ${response.status}`,
    );
  }
  return response.json();
}

// 处理API错误
function handleApiError(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }
  return "未知错误";
}

// 分类管理API
export const categoryApi = {
  // 获取分类列表
  async getCategories(
    params?: CategoryListParams,
  ): Promise<CategoryResponse[]> {
    const searchParams = new URLSearchParams();
    if (params?.parent_id !== undefined)
      searchParams.append("parent_id", params.parent_id?.toString() || "");
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/accounting/categories?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<CategoryResponse[]>(response);
  },

  // 获取所有分类（包括子分类）
  async getAllCategories(params?: {
    skip?: number;
    limit?: number;
  }): Promise<CategoryResponse[]> {
    const searchParams = new URLSearchParams();
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/accounting/categories/all?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<CategoryResponse[]>(response);
  },

  // 获取分类层级结构
  async getCategoriesHierarchy(): Promise<CategoryWithChildren[]> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/categories/hierarchy`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<CategoryWithChildren[]>(response);
  },

  // 获取单个分类
  async getCategory(categoryId: number): Promise<CategoryResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/categories/${categoryId}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<CategoryResponse>(response);
  },

  // 创建分类
  async createCategory(category: CategoryCreate): Promise<CategoryResponse> {
    const response = await fetch(`${apiConfig.baseURL}/accounting/categories`, {
      method: "POST",
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
      body: JSON.stringify(category),
    });

    return handleResponse<CategoryResponse>(response);
  },

  // 批量创建分类
  async batchCreateCategories(
    batch: BatchCategoryCreate,
  ): Promise<CategoryResponse[]> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/categories/batch`,
      {
        method: "POST",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
        body: JSON.stringify(batch),
      },
    );

    return handleResponse<CategoryResponse[]>(response);
  },

  // 更新分类
  async updateCategory(
    categoryId: number,
    category: CategoryUpdate,
  ): Promise<CategoryResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/categories/${categoryId}`,
      {
        method: "PUT",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
        body: JSON.stringify(category),
      },
    );

    return handleResponse<CategoryResponse>(response);
  },

  // 删除分类
  async deleteCategory(categoryId: number): Promise<void> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/categories/${categoryId}`,
      {
        method: "DELETE",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<void>(response);
  },
};

// 账户管理API
export const accountApi = {
  // 获取账户列表
  async getAccounts(params?: AccountListParams): Promise<AccountResponse[]> {
    const searchParams = new URLSearchParams();
    if (params?.is_active !== null && params?.is_active !== undefined)
      searchParams.append("is_active", params.is_active.toString());
    if (params?.account_type)
      searchParams.append("account_type", params.account_type);
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/accounting/accounts?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<AccountResponse[]>(response);
  },

  // 获取单个账户
  async getAccount(accountId: number): Promise<AccountResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/accounts/${accountId}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<AccountResponse>(response);
  },

  // 创建账户
  async createAccount(account: AccountCreate): Promise<AccountResponse> {
    const response = await fetch(`${apiConfig.baseURL}/accounting/accounts`, {
      method: "POST",
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
      body: JSON.stringify(account),
    });

    return handleResponse<AccountResponse>(response);
  },

  // 更新账户
  async updateAccount(
    accountId: number,
    account: AccountUpdate,
  ): Promise<AccountResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/accounts/${accountId}`,
      {
        method: "PUT",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
        body: JSON.stringify(account),
      },
    );

    return handleResponse<AccountResponse>(response);
  },

  // 删除账户
  async deleteAccount(accountId: number): Promise<void> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/accounts/${accountId}`,
      {
        method: "DELETE",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<void>(response);
  },
};

// 项目管理API
export const projectApi = {
  // 获取项目列表
  async getProjects(params?: ProjectListParams): Promise<ProjectResponse[]> {
    const searchParams = new URLSearchParams();
    if (params?.is_active !== null && params?.is_active !== undefined)
      searchParams.append("is_active", params.is_active.toString());
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/accounting/projects?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<ProjectResponse[]>(response);
  },

  // 获取单个项目
  async getProject(projectId: number): Promise<ProjectResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/projects/${projectId}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<ProjectResponse>(response);
  },

  // 创建项目
  async createProject(project: ProjectCreate): Promise<ProjectResponse> {
    const response = await fetch(`${apiConfig.baseURL}/accounting/projects`, {
      method: "POST",
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
      body: JSON.stringify(project),
    });

    return handleResponse<ProjectResponse>(response);
  },

  // 更新项目
  async updateProject(
    projectId: number,
    project: ProjectUpdate,
  ): Promise<ProjectResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/projects/${projectId}`,
      {
        method: "PUT",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
        body: JSON.stringify(project),
      },
    );

    return handleResponse<ProjectResponse>(response);
  },

  // 删除项目
  async deleteProject(projectId: number): Promise<void> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/projects/${projectId}`,
      {
        method: "DELETE",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<void>(response);
  },
};

// 交易管理API
export const transactionApi = {
  // 获取交易列表
  async getTransactions(
    params?: TransactionListParams,
  ): Promise<TransactionList> {
    const searchParams = new URLSearchParams();
    if (params?.transaction_type)
      searchParams.append("transaction_type", params.transaction_type);
    if (params?.account_id !== undefined)
      searchParams.append("account_id", params.account_id?.toString() || "");
    if (params?.category_id !== undefined)
      searchParams.append("category_id", params.category_id?.toString() || "");
    if (params?.project_id !== undefined)
      searchParams.append("project_id", params.project_id?.toString() || "");
    if (params?.member_id !== undefined)
      searchParams.append("member_id", params.member_id?.toString() || "");
    if (params?.start_date)
      searchParams.append("start_date", params.start_date);
    if (params?.end_date) searchParams.append("end_date", params.end_date);
    if (params?.search) searchParams.append("search", params.search);
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/accounting/transactions?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<TransactionList>(response);
  },

  // 获取单个交易
  async getTransaction(transactionId: number): Promise<TransactionResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/transactions/${transactionId}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<TransactionResponse>(response);
  },

  // 创建交易
  async createTransaction(
    transaction: TransactionCreate,
  ): Promise<TransactionResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/transactions`,
      {
        method: "POST",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
        body: JSON.stringify(transaction),
      },
    );

    return handleResponse<TransactionResponse>(response);
  },

  // 批量创建交易
  async batchCreateTransactions(
    batch: BatchTransactionCreate,
  ): Promise<TransactionResponse[]> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/transactions/batch`,
      {
        method: "POST",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
        body: JSON.stringify(batch),
      },
    );

    return handleResponse<TransactionResponse[]>(response);
  },

  // 更新交易
  async updateTransaction(
    transactionId: number,
    transaction: TransactionUpdate,
  ): Promise<TransactionResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/transactions/${transactionId}`,
      {
        method: "PUT",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
        body: JSON.stringify(transaction),
      },
    );

    return handleResponse<TransactionResponse>(response);
  },

  // 删除交易
  async deleteTransaction(transactionId: number): Promise<void> {
    const response = await fetch(
      `${apiConfig.baseURL}/accounting/transactions/${transactionId}`,
      {
        method: "DELETE",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<void>(response);
  },
};

// 统计API
export const statisticsApi = {
  // 获取交易统计摘要
  async getTransactionSummary(
    params?: StatisticsParams,
  ): Promise<TransactionSummary> {
    const searchParams = new URLSearchParams();
    if (params?.start_date)
      searchParams.append("start_date", params.start_date);
    if (params?.end_date) searchParams.append("end_date", params.end_date);

    const response = await fetch(
      `${apiConfig.baseURL}/accounting/statistics/summary?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<TransactionSummary>(response);
  },

  // 获取分类统计
  async getCategoryStatistics(
    params?: StatisticsParams,
  ): Promise<CategorySummary[]> {
    const searchParams = new URLSearchParams();
    if (params?.start_date)
      searchParams.append("start_date", params.start_date);
    if (params?.end_date) searchParams.append("end_date", params.end_date);

    const response = await fetch(
      `${apiConfig.baseURL}/accounting/statistics/categories?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<CategorySummary[]>(response);
  },

  // 获取账户统计
  async getAccountStatistics(
    params?: StatisticsParams,
  ): Promise<AccountSummary[]> {
    const searchParams = new URLSearchParams();
    if (params?.start_date)
      searchParams.append("start_date", params.start_date);
    if (params?.end_date) searchParams.append("end_date", params.end_date);

    const response = await fetch(
      `${apiConfig.baseURL}/accounting/statistics/accounts?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<AccountSummary[]>(response);
  },

  // 获取项目统计
  async getProjectStatistics(
    params?: StatisticsParams,
  ): Promise<ProjectSummary[]> {
    const searchParams = new URLSearchParams();
    if (params?.start_date)
      searchParams.append("start_date", params.start_date);
    if (params?.end_date) searchParams.append("end_date", params.end_date);

    const response = await fetch(
      `${apiConfig.baseURL}/accounting/statistics/projects?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<ProjectSummary[]>(response);
  },
};

// 导出所有API
export const accountingApi = {
  categories: categoryApi,
  accounts: accountApi,
  projects: projectApi,
  transactions: transactionApi,
  statistics: statisticsApi,
};

// 导出错误处理函数
export { handleApiError };
